import { mapState } from 'vuex';
import { formatDate } from '@/utils/date';
import separateHeader from '@/components/separate-header.vue';

import { fetchProductDetail } from '@/api/product.js';
import { createAndDeleteCollection ,detailCollection } from '@/api/collection.js';
import { createCart } from '@/api/cart.js';

export default {
	components: {
		separateHeader
	},
	data() {
		return {
			options: [{
				icon: 'shop',
				text: '店铺'
			}, {
				icon: 'star',
				text: '收藏'
			}, {
				icon: 'cart',
				text: '购物车'
			}],
			buttonGroup: [{
			  text: '加入购物车',
			  backgroundColor: '#ff0000',
			  color: '#fff'
			},
			{
			  text: '立即购买',
			  backgroundColor: '#ffa200',
			  color: '#fff'
			}],
			
			sku: 0,
			product: {},
			
			attributeList: [],     //属性列表
			skuList: [],           //sku列表
			specClass: 'none',     //属性面板显示
			specSelected: [],      //选中属性
			specList: [],          //属性名称
			specChildList: [],     //属性类目
			
			imgList: [],
			detailHtml: "",
			favorite: false,
		};
	},
	onLoad(options) {
		//商品标识码
		this.sku = options.sku;
		//加载数据
		this.loadData();
	},
	filters: {
		formatDateTime(time) {
			if (time == null || time === '') {
				return 'N/A';
			}
			let date = new Date(time);
			return formatDate(date, 'yyyy-MM-dd')
		},
	},
	computed: {
		...mapState(['hasLogin'])
	},
	methods: {
		async loadData() {
			fetchProductDetail(this.sku).then(response => {
				this.product = response.data.productEntity;
				this.attributeList = response.data.attributeList;
				this.skuList = response.data.skuList;
				
				//设置标题
				uni.setNavigationBarTitle({
					title: this.product.title
				})
				//设置轮播图片
				let tempPics = this.product.albumPics.split(',');
				tempPics.unshift(this.product.pic);
				for (let item of tempPics) {
					if (item != null && item != '') {
						this.imgList.push({
							src: item
						});
					}
				}
				
				/**
				 * 设置详情 富文本
				 * 解决图片显示问题
				 */
				if(this.product.detailHtml){
					this.detailHtml = this.product.detailHtml.replace(/\<img/gi,'<img style="max-width:100%;height:auto;display:block;"');
				}
				
				//查询用户收藏
				this.queryCollection();
				//初始化商品属性
				this.initSpecList();
			})
		},

		//查询用户收藏
		queryCollection() {
			if (this.hasLogin) {
				let params = this.product.sku;
				detailCollection(params).then(response => {
					//查询出数据说明已经收藏
					if(response.data!=null){
						this.favorite = true;
						//显示收藏图标
						this.showFavorite();
					}
				});
			}
		},
		
		//设置商品规格
		initSpecList() {
			
			for (let i = 0; i < this.attributeList.length; i++) {
				let item = this.attributeList[i];
				
				this.specList.push({
					id: item.id,
					name: item.title
				});
				
				let inputList = item.inputList.split(/[\n\s+,，；;]/g);;
				for (let j = 0; j < inputList.length; j++) {
					this.specChildList.push({
						pid: item.id,
						pname: item.title,
						name: inputList[j]
					});
				}
				
			}
			let availAbleSpecSet = new Set();
			for (let i = 0; i < this.skuList.length; i++) {
				let spDataArr = this.skuList[i].spData.split(';');
				for (let j = 0; j < spDataArr.length; j++) {
					let sp = spDataArr[j].split(':');
					availAbleSpecSet.add(sp[1]);
				}
			}
			
			// 根据商品sku筛选出可用规格
			this.specChildList = this.specChildList.filter(item => {
				return availAbleSpecSet.has(item.name)
			});
			
			// 规格 默认选中第一条
			this.specList.forEach(item => {
				for (let cItem of this.specChildList) {
					if (cItem.pid === item.id) {
						this.$set(cItem, 'selected', true);
						this.specSelected.push(cItem);
						this.changeSpecInfo();
						break;
					}
				}
			})
		},

		//规格弹窗开关
		toggleSpec() {
			if (this.specClass === 'show') {
				this.specClass = 'hide';
				setTimeout(() => {
					this.specClass = 'none';
				}, 250);
			} else if (this.specClass === 'none') {
				this.specClass = 'show';
			}
		},
		//选择规格
		selectSpec(index, pid) {
			let list = this.specChildList;
			list.forEach(item => {
				if (item.pid === pid) {
					this.$set(item, 'selected', false);
				}
			})

			this.$set(list[index], 'selected', true);
			
			this.specSelected = [];
			list.forEach(item => {
				if (item.selected === true) {
					this.specSelected.push(item);
				}
			})
			this.changeSpecInfo();

		},
		
		stopPrevent() {},
		
		//当商品规格改变时，修改商品信息
		changeSpecInfo() {
			let skuStock = this.getSkuStock();
			if (skuStock != null) {
				this.product.price = skuStock.price;
				this.product.pic = skuStock.pic;
				this.product.stock = skuStock.stock;
			}
		},
		
		//获取当前选中商品的SKU
		getSkuStock() {
			for (let i = 0; i < this.skuList.length; i++) {
				let spDataArr = this.skuList[i].spData.split(';');
				let availAbleSpecSet = new Map();
				for (let j = 0; j < spDataArr.length; j++) {
					let sp = spDataArr[j].split(':');
					availAbleSpecSet.set(sp[0],sp[1]);
				}
				let correctCount = 0;
				for (let item of this.specSelected) {
					let value = availAbleSpecSet.get(item.pname);
					if (value != null && value == item.name) {
						correctCount++;
					}
				}
				if (correctCount == this.specSelected.length) {
					return this.skuList[i];
				}
			}
			return null;
		},
		
		//检查登录状态并弹出登录框
		checkForLogin() {
			if (!this.hasLogin) {
				uni.showModal({
					title: '提示',
					content: '你还没登录，是否要登录？',
					confirmText:'登录',
					cancelText:'取消',
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/user/login/login'
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
				return false;
			} else {
				return true;
			}
		},
		
		/**
		 * 底部导航
		 * 左侧点击事件:店铺、收藏、购物车
		 */
		onClick(e) {
			//文字
			let text = e.content.text;
			if(text == "店铺"){
				let url = '/pages/shop/shop?id='+this.product.shopId;
				uni.navigateTo({
					url
				});
			}else if(text == "收藏"){
				this.toFavorite()
			}else if(text == "购物车"){
				uni.switchTab({
					url: '/pages/cart/cart'
				})
			}
		},
		
		//收藏
		toFavorite() {
			if (!this.checkForLogin()) {
				return;
			}
			let data = {
				sku: this.product.sku,
			}
			createAndDeleteCollection(data).then(response => {
				this.favorite = !this.favorite;
				//显示收藏图标
				this.showFavorite();
				
			});
		},
		//显示收藏图标
		showFavorite(){
			let favIcon = this.favorite ? 'star-filled' : 'star';
			this.options = [{
				icon: 'shop',
				text: '店铺'
			}, {
				icon: favIcon,
				text: '收藏'
			}, {
				icon: 'cart',
				text: '购物车'
			}];
		},

		/**
		 * 底部导航
		 * 右侧按钮组点击事件:加入购物车、立即购买
		 */
		buttonClick(e) {
			//文字
			let text = e.content.text;
			if(text == "加入购物车"){
				this.addToCart();
			}else if(text == "立即购买"){
				this.buy();
			}
		},
		//加入购物车
		addToCart() {
			if (!this.checkForLogin()) {
				return;
			}
			let skuStock = this.getSkuStock();
			
			let data = {
				sku: this.product.sku,
				skuCode: skuStock.skuCode,
				number: 1
			}
			createCart(data).then(response => {
				uni.showToast({
					title: "添加购物车成功！",
					icon: 'none'
				});
			});
		},
		//立即购买
		buy() {
			if (!this.checkForLogin()) {
				return;
			}
			let skuStock = this.getSkuStock();
			let skuCodes = [skuStock.skuCode];
			uni.navigateTo({
				url: `/pages/order/order?skuCodes=${JSON.stringify(skuCodes)}`
			})
		},
		
	}
}